package com.wanli.agent.mine;

import android.os.Bundle;
import android.text.TextUtils;
import android.widget.EditText;
import android.widget.TextView;

import com.google.gson.Gson;
import com.wanli.agent.R;
import com.wanli.agent.base.BaseActivity;
import com.wanli.agent.base.DataCallBack;
import com.wanli.agent.bean.BaseResponseBean;
import com.wanli.agent.bean.UserInfoBean;
import com.wanli.agent.event.UpDateNameEvent;
import com.wanli.agent.homepage.model.HomePageModelImpl;
import com.wanli.agent.utils.SPManager;
import com.wanli.agent.utils.ToastUtil;
import com.wanli.agent.widget.AppTitleBar;
import com.wanli.agent.widget.ViewLoading;

import org.greenrobot.eventbus.EventBus;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class UpdateNameActivity extends BaseActivity {

    @BindView(R.id.title_bar)
    AppTitleBar titleBar;
    @BindView(R.id.edit_name)
    EditText editName;
    @BindView(R.id.tv_commit)
    TextView tvCommit;
    private String name;
    private UserInfoBean userInfoBean;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_update_name);
        ButterKnife.bind(this);
        name = getIntent().getStringExtra("name");
        userInfoBean = new Gson().fromJson(SPManager.getInstance().getUserInfoJson(), UserInfoBean.class);
        if (!TextUtils.isEmpty(name)) {
            editName.setText(name);
            editName.setSelection(name.length());
        }
    }

    @OnClick(R.id.tv_commit)
    public void onViewClicked() {
        String name = editName.getText().toString();
        if (TextUtils.isEmpty(name)) {
            ToastUtil.showShort("请输入名称");
        }
        ViewLoading.showProgress(mActivity);
        new HomePageModelImpl().requestAgentUpdateName(name, new DataCallBack<BaseResponseBean>() {
            @Override
            public void onSuccessful(BaseResponseBean bean) {
                ToastUtil.showShort("修改成功");
                userInfoBean.getData().setName(name);
                SPManager.getInstance().saveUserInfoJson(new Gson().toJson(userInfoBean));
                EventBus.getDefault().post(new UpDateNameEvent());
                finish();
            }

            @Override
            public void onFailed(String msg, String code) {

            }
        });
    }
}
